var Cliente=Ext.data.Record.create([
	{
		name: 'id'
	}, {
		name: 'name',
       	type: 'string'
	}, {
		name: 'codigo',
       	type: 'string'
	}, {
		name: 'email',
       	type: 'string'
	}, {
		name: 'telefone',
       	type: 'string'
	}]);

var dsClientes = new Ext.data.Store({
    id: 'cliente-store',
    restful: true,
    autoSave: false,
    prettyUrls: true,
	remoteSort: true,
    sortInfo: {field:'name', direction:'ASC'},
    baseParams: {'start': 0, 'limit': 15},
    autoLoad: false,
    successProperty: 'success',

    proxy: new Ext.data.HttpProxy({
    	url: 'clientes'
    }),

    reader: new Ext.data.JsonReader({
        root: 'data',
        totalProperty: 'total',
        idProperty: 'id',
        fields: [
            'id', 'name', 'email', 'telefone'
        ]
    }, Cliente),
    
    writer: new Ext.data.JsonWriter({
        encode: false,
        writeAllFields: true
    })
});

dsClientes.on('write', function(store, action, data, response, rs) {
	
	switch(action) {
		case 'destroy': 
			if (response.raw.success) 
				formClientes.modeInsert();

			dsClientes.reload();			
			Ext.MessageBox.alert('Status', response.raw.message);
		  break;
		case 'update':
			Ext.MessageBox.alert('Status', response.raw.message);
			dsClientes.reload();	
		  break;	
	}	  
});

var gridClientes={
	xtype: 'grid',
    title: 'Lista de clientes',
    id: 'clientes-grid',
    x: 5,
    y: 141,
    width: 576,
    height: 393,
    border: true,
	ds: dsClientes,
    sm: new Ext.grid.RowSelectionModel({
        singleSelect: true,
        listeners: {
            rowselect: function(sm, row, rec) {
            	formClientes.modeEdit(rec);
            }
        }
   }),
   columns:[
     {
         xtype: 'gridcolumn',
         dataIndex: 'id',
         header: 'Id',
         sortable: true,
         width: 30
     },
     {
    	 xtype: 'gridcolumn',
    	 dataIndex: 'codigo',
    	 header: 'Código',
    	 sortable: true,
    	 width: 80,
     },
     {
         xtype: 'gridcolumn',
         dataIndex: 'name',
         header: 'Nome',
         sortable: true,
         width: 200,
     },
     {
         xtype: 'gridcolumn',
         dataIndex: 'telefone',
         header: 'Telefone',
         sortable: true,
         width: 100
     },
     {
         xtype: 'gridcolumn',
         dataIndex: 'email',
         header: 'Email',
         sortable: true,
         width: 162
     }],
   bbar: new Ext.PagingToolbar({
       pageSize: 15,
       store: dsClientes,
       displayInfo: true,
       displayMsg: 'Exibindo registros {0} - {1} of {2}',
       emptyMsg: ""
   }),
};

var formClientes=new Ext.FormPanel({
    id: 'clientes-form',
    frame: false,
    border: false,
    labelAlign: 'left',
    bodyStyle:'padding:5px',
    defaultType: 'textfield',
    layout: 'absolute',
    
    store: dsClientes,
    grid: gridClientes,
    
    modeInsert: function() {    	
    	Ext.getCmp('botao-novo-clientes').disable();
    	Ext.getCmp('botao-deletar-clientes').disable();
    	
    	gridClientes.sm.clearSelections();
    	formClientes.getForm().reset();
    },
    
    modeEdit: function(obj) {    	
    	Ext.getCmp('botao-novo-clientes').enable();
    	Ext.getCmp('botao-deletar-clientes').enable();
    	
    	if (typeof obj=='object')
        	this.getForm().loadRecord(obj);
        else {
			Ext.getCmp('cliente-id').setValue(obj);
			gridClientes.sm.clearSelections();
			dsClientes.reload();
        }        	
    },
    
    bindRecord: function(obj) {
    	
		obj.set("name",this.getForm().findField('name').getRawValue());
		obj.set("codigo",this.getForm().findField('codigo').getRawValue());
		obj.set("email",this.getForm().findField('email').getRawValue());
		obj.set("telefone",this.getForm().findField('telefone').getRawValue()); 
		
		return obj; 
    },
    
    saveRecord: function() {
    	var rec=this.grid.sm.getSelected();
    		
    	if (rec)
    		this.editRecord(this.bindRecord(rec));
    	else
    		this.insertRecord(this.bindRecord(new Cliente()));
    },
    
    insertRecord: function(rec) {
    	
		if (this.getForm().isValid()) {
			
			this.store.add(rec);
			
			Ext.Ajax.request({
				url: 'clientes',
				method: "POST",
				success: function(response, request) {
					var resp=Ext.decode(response.responseText);                        					   
					Ext.MessageBox.alert('Status', resp.message);                        					   
					formClientes.modeEdit(resp.id);                        					  
				},
				failure: function(response, request) {
					var resp=Ext.decode(response.responseText);                        					   
					Ext.MessageBox.alert('Status', resp.message);
				},
				headers: {
					'Content-Type': 'application/json; charset=UTF-8'
				},
				params: '{"data":'+Ext.encode(rec.data)+'}'
			});                        			
		} 
		else
			Ext.MessageBox.alert('Status', "Registro não é válido para ser inserido!");
    },
    
    editRecord: function(rec) {
		try
		{
			if (!rec.modified)
				throw("Nenhuma informação alterada no registro.");
			
			if (!this.getForm().isValid())
				throw("Registro não é válido para ser atualizado!");
			
			this.store.save();
		}
		catch (e)
		{
			Ext.MessageBox.alert('Status', e);
		}				
    },
    
    deleteRecord: function() {
    	this.store.remove(this.grid.sm.getSelected());
    	this.store.save();
    },
    
    items: [
			{
			    xtype: 'hidden',
			    name: 'id', 
			    id: 'cliente-id'
			},
			{
			    xtype: 'label',
			    x: 5,
			    y: 5,
			    text: 'Código:'
			},    
            {
                xtype: 'textfield',
                x: 5,
                y: 20,
                name: 'codigo',
                allowBlank: false
            },
			{
			    xtype: 'label',
			    x: 170,
			    y: 5,
			    text: 'Nome:' 
			},    
            {
                xtype: 'textfield',
                x: 170,
                y: 20,
                name: 'name',
                width: 411,
                //allowBlank: false
            },
			{
			    xtype: 'label',
			    x: 5,
			    y: 45,
			    text: 'Telefone:' 
			},
			{
                xtype: 'textfield',
                x: 5,
                y: 60,
                name: 'telefone'                                
            },
            {
			    xtype: 'label',
			    x: 170,
			    y: 45,
			    text: 'Email:' 
			},
			{
                xtype: 'textfield',
                x: 170,
                y: 60,
                name: 'email',
                width: 411,
                //vtype: 'email'
            }
			,gridClientes
    ],
    tbar: {
        xtype: 'toolbar',
        items: [
            {
                xtype: 'buttongroup',
                title: '',
                columns: 5,
                frame: false,
                border: false,
                items: [
                    {
                        xtype: 'button',
                        id: 'botao-salvar-clientes',
                        text: 'Salvar',
                        width: 60,
                        iconCls:'save',
                        handler: function() 
				        	{
                        	this.ownerCt.ownerCt.ownerCt.saveRecord();
				        	}
                    },
                    {
                        xtype: 'button',
                        id: 'botao-novo-clientes',
                        text: 'Novo',
                        width: 60,
                        disabled: true,
                        iconCls:'add',
                        handler: function()	{
                        	this.ownerCt.ownerCt.ownerCt.modeInsert();
			        	}
                    },
                    {
                        xtype: 'button',
                        id: 'botao-deletar-clientes',
                        text: 'Deletar',
                        width: 60,
                        disabled: true,
                        iconCls:'remove',
                        handler: function() {  
                        	this.ownerCt.ownerCt.ownerCt.deleteRecord();
                    	}
                    }
                ]
            }
        ] 
	}    
});

MyDesktop.Clientes=Ext.extend(Ext.app.Module, {
    id:'clientes-win',
    init : function(){
        this.launcher = {
            text: 'Clientes',
            iconCls:'icon-grid',
            handler : this.createWindow,
            scope: this
        }
    },
    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('clientes-win');
        if(!win){
            win = desktop.createWindow({            		
            	id: 'clientes-win',
                title:'Clientes',
                width:600,
                height:600,
                iconCls: 'icon-grid',
                shim:false,
                animCollapse:false,
                constrainHeader:true,
                closeAction: 'hide',
                layout: 'fit',
                items: formClientes
            }); 
            
            win.on({
                'activate': {
                    fn: function() {
                    	dsClientes.reload();
                    }
                }});
        }   
        win.show();
    }
});